package com.his.his_system.common.handler;

import cn.hutool.json.JSONUtil;
import com.his.his_system.common.util.ResultAdvice;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 */
@Component
public class AuthenticationFail implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception)
            throws IOException, ServletException {

//自定义返回类型
        ResultAdvice fail = null;
        if (exception.getClass() == BadCredentialsException.class) {
//            账号或密码认证失败
            fail = ResultAdvice.fail("账号或密码错误", "406");
        }else if (exception.getClass() == InternalAuthenticationServiceException.class) {
            fail = ResultAdvice.fail(exception.getMessage(), "407");
        }
//        打印异常信息
        System.out.println(exception.getMessage());

        response.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台

        response.getWriter().write(JSONUtil.toJsonStr(fail));
    }
}
